package org.example.webdav.resources;

import com.github.sardine.Sardine;
import com.github.sardine.impl.SardineImpl;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;

@Component
public class WebDavProtocolResolver implements  ProtocolResolver, ResourceLoaderAware {
    public static final String WEBDAV_RESOURCE_PREFIX = "webdav://";
    @Autowired
    private WebDavProperies webDavProperies;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        if(DefaultResourceLoader.class.isAssignableFrom(resourceLoader.getClass())) {
            ((DefaultResourceLoader)resourceLoader).addProtocolResolver(this);
        } else {
            System.out.println("Could not assign protocol loader.");
        }
    }

    @Override
    public Resource resolve(String location, ResourceLoader resourceLoader) {
        if(location.startsWith(WEBDAV_RESOURCE_PREFIX)){

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            webDavProperies.getCreds().forEach(cred->credentialsProvider.setCredentials(cred.getAuthScope(),cred.getCredentials()));
            Sardine client = new SardineImpl(
                    HttpClientBuilder.create()
                            .setDefaultCredentialsProvider(credentialsProvider)
                            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()));

            try {
                return new WebDavResource(client, location.substring(WEBDAV_RESOURCE_PREFIX.length()));
            } catch (IOException | URISyntaxException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
